package com.amado.course53EncodeDecode;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author Administrator
 */
public class AESUtil {
    private static final int LENGTH_128BIT = 16;
    private static final String SECRET_KEY = "AES";
    public static final String CHARSET_NAME = "utf-8";

    // 加密
    public static String encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != LENGTH_128BIT) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes(CHARSET_NAME);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, SECRET_KEY);
        //"算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance(SECRET_KEY);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(CHARSET_NAME));
        //此处使用BASE64做转码功能，同时能起到2次加密的作用。
        return new BASE64Encoder().encode(encrypted);
    }

    // 解密
    public static String decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != LENGTH_128BIT) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes(CHARSET_NAME);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, SECRET_KEY);
            Cipher cipher = Cipher.getInstance(SECRET_KEY);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            //先用base64解密
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, CHARSET_NAME);
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        /*
         * 此处使用AES-128-ECB加密模式，key需要为16位。
         */
        String cKey = "1234567890123456";
        // 需要加密的字串
        String cSrc = "我的密码";
        System.out.println(cSrc);
        // 加密,第一次加密很慢，后面会有缓存
        long startTime = System.currentTimeMillis();
        String enString = AESUtil.encrypt(cSrc, cKey);
        long endTime = System.currentTimeMillis();
        System.out.println("加密后的字串是：" + enString + " 耗时：" + (endTime - startTime));


        // 解密
        startTime = System.currentTimeMillis();
        String deString = AESUtil.decrypt(enString, cKey);
        endTime = System.currentTimeMillis();
        System.out.println("解密后的字串是：" + deString + " 耗时：" + (endTime - startTime));
    }
}